const api = require('../../utils/api')

Page({
  data: {
    keyword: '',
    searchHistory: [],
    searchResults: [],
    loading: false
  },

  onLoad(options) {
    // 如果有传入的关键词，直接搜索
    const { keyword } = options;
    if (keyword) {
      this.setData({ keyword });
      this.search(keyword);
    }
    // 获取搜索历史
    this.getSearchHistory();
  },

  // 输入搜索关键词
  onInput(e) {
    const keyword = e.detail.value;
    this.setData({ keyword });
    if (!keyword) {
      this.setData({ searchResults: [] });
    }
  },

  // 确认搜索
  onSearch() {
    const { keyword } = this.data;
    if (!keyword.trim()) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }
    this.search(keyword);
  },

  // 搜索方法
  async search(keyword) {
    this.setData({ loading: true });
    try {
      console.log('开始搜索:', keyword);
      const res = await api.searchProducts(keyword);
      console.log('搜索结果:', res);
      
      if (res && res.data) {
        const searchResults = Array.isArray(res.data) ? res.data : (res.data.content || []);
        this.setData({ 
          searchResults: searchResults.map(item => ({
            id: item.id,
            name: item.name,
            description: item.description,
            price: item.price,
            images: [item.imageUrl]
          }))
        });
        this.saveSearchHistory(keyword);
      } else {
        console.error('搜索返回数据格式错误:', res);
        wx.showToast({
          title: '搜索失败，数据格式错误',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('搜索出错:', error);
      wx.showToast({
        title: error.message || '搜索失败，请重试',
        icon: 'none',
        duration: 2000
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 清空搜索
  clearSearch() {
    this.setData({
      keyword: '',
      searchResults: []
    });
  },

  // 获取搜索历史
  getSearchHistory() {
    const searchHistory = wx.getStorageSync('searchHistory') || [];
    this.setData({ searchHistory });
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    let { searchHistory } = this.data;
    // 去重
    searchHistory = searchHistory.filter(item => item !== keyword);
    // 添加到开头
    searchHistory.unshift(keyword);
    // 最多保存10条
    searchHistory = searchHistory.slice(0, 10);
    
    this.setData({ searchHistory });
    wx.setStorageSync('searchHistory', searchHistory);
  },

  // 清空搜索历史
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ searchHistory: [] });
          wx.removeStorageSync('searchHistory');
        }
      }
    });
  },

  // 点击历史记录
  onHistoryTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({ keyword });
    this.search(keyword);
  },

  // 跳转到商品详情
  goToProduct(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/product/product?id=${id}&from=search`
    });
  }
}) 